import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

//组件状态管理
export default new Vuex.Store({
  state: {
    //学生信息存值
    studentData:{
        currentPage:2,
        pageSize:5,
        totalPage:0,
        totalStudent:0,
        students:[]
    },

    //班级信息存值
    classesData:{},

    //搜索值存值
    searchData:{
      searchType:'name',
      searchData:'',
    },

    countNumber:0,
  },

  getters: {
  },

  mutations: {
    testFoo(){
      console.log('hi')
    },
    //点赞--------------------------
    incrementF(state){
      state.countNumber++;
    },  
    decrementF(state){
      state.countNumber--;
    },    
    transValueFoo(state, newValue){
      state.countNumber = newValue;
    },

    //获取学生函数的操作后解决actions方法无法直接修改state数据问题-----------------------
    getStudentsAfter(state,newData){
      state.studentData = {
        ...state.studentData,
        ...newData
      };
    },
    getClassesAfter(state,newValue){
      state.classesData = newValue;
      console.log(state.classesData);
    },

    //分页功能的函数------------------------------------------
    togglePageData(state,newValue){
      //newValue是对象
      console.log(newValue);

      switch(newValue.doWhat){
        //修改pageSize
        case 'TogglePageSize':state.studentData.pageSize = newValue.pageSize;break;
        //跳转首页
        case 'ToggleFirstPage':state.studentData.currentPage = 1;break;
        //跳转尾页
        case 'ToggleLastPage':state.studentData.currentPage = state.studentData.totalPage;break;
        //跳转上一页
        case 'prevPage':
          if(state.studentData.currentPage > 1){
            state.studentData.currentPage --;
          }else{
            alert("无上一页了！");
          }
          break;
        //跳转下一页
        case 'nextPage':
          if(state.studentData.currentPage < state.studentData.totalPage){
            state.studentData.currentPage ++;
          }else{
            alert("无下一页了！");
          }
          break;
      }    
    },
    
    //搜索功能的函数---实时检测搜索值得变化
    toggleSearchData(state,newValue){
      state.searchData = newValue;
    },

    

  },

  //actions写异步函数
  //调用state数据 直接
  actions: {

    //新增，修改，学生列表组件都要用！
    async getStudents(context){
      const {data} = await axios({
        url:'/students/getStudents',
        method:'get',
        params:{
          ...context.state.studentData,
          ...context.state.searchData,
          students:[]
        }
      });
      if (data.status) {
        context.commit('getStudentsAfter',data.data);
        console.log(data);
      }else{
        alert(data.message + '  详情请看控制台');
        console.log(data);
      }  
    },

    async getClasses(context){
      const {data} = await axios({
        url:'/classes/getClasses',
        type:'get'
      })
      if(data.status){
        console.log(data);
        context.commit('getClassesAfter',data.data);
      }else{
        alert(data.message)
      }
    }
  },

  modules: {
  }

})
